package com.ljw.zookeeper;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: lijunwei
 * @Time: 2019/8/10 20:35
 */
public class ServiceDiscovery {
    List<String> serviceRepos = new ArrayList<String>();

    private static final String REGISTRY_ROOT = "/registry";
    private static CuratorFramework client = null;

    static {
        client=  CuratorFrameworkFactory.builder()
                .connectString("127.0.0.1:2181")
                .sessionTimeoutMs(3000)
                .connectionTimeoutMs(5000)
                .retryPolicy(new ExponentialBackoffRetry(1000, 10))
                .build();
        client.start();
    }

    public void init(String serviceName) throws Exception {
        String path = REGISTRY_ROOT + "/" + serviceName;

        serviceRepos= client.getChildren().forPath(path);

        registryWatcher(path);
    }

    public  String getServiceEndPoint(){
        RandomLoadBalance loadBalance = new RandomLoadBalance();
       return loadBalance.doSelect(serviceRepos);
    }


    public void registryWatcher(final String path) throws Exception {
        PathChildrenCache pathChildrenCache = new PathChildrenCache(client, path, true);
        PathChildrenCacheListener pathChildrenCacheListener = new PathChildrenCacheListener() {
            public void childEvent(CuratorFramework curatorFramework, PathChildrenCacheEvent pathChildrenCacheEvent) throws Exception {
                serviceRepos = curatorFramework.getChildren().forPath(path);
            }
        };
        pathChildrenCache.getListenable().addListener(pathChildrenCacheListener);
        pathChildrenCache.start();

    }

    public static void main(String[] args) throws Exception {
        ServiceDiscovery serviceDiscovery = new ServiceDiscovery();
        serviceDiscovery.init("product-service");

        for (int i = 0; i <20 ; i++) {
            System.out.println(serviceDiscovery.getServiceEndPoint());
            Thread.sleep(2000);
        }
    }
}
